package teleradiologia.repository;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.security.providers.encoding.Md5PasswordEncoder;

import teleradiologia.domain.Person;
import teleradiologia.utils.HibernateUtil;

public class PersonDaoImpl implements PersonDao {
	private org.springframework.security.providers.encoding.BaseDigestPasswordEncoder encoder = new Md5PasswordEncoder();

	@Override
	public long create(Person person) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		person.setPassword(encoder.encodePassword(person.getPassword(), person
				.getUsername()));

		long id = (Long) session.save(person);

		tx.commit();
		session.close();

		return ++id;
	}

	@Override
	public void delete(Person person) {
		if (person != null) {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction tx = session.beginTransaction();

			session.delete(person);

			tx.commit();
			session.close();
		}
	}

	@Override
	public Person getById(long id) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		Person person = (Person) session.get(Person.class, new Long(id));

		tx.commit();
		session.close();

		return person;
	}

	@Override
	public void update(Person person) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		if (person.getPassword().length() < 20) {
			person.setPassword(encoder.encodePassword(person.getPassword(),
					person.getUsername()));
		}

		session.update(person);

		tx.commit();
		session.close();
	}

	@Override
	public Person getByLogin(String login) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		Person person = (Person) session.createQuery(
				"from Person person where person.login = :login").setString(
				"login", login).uniqueResult();

		tx.commit();
		session.close();

		return person;
	}
}
